package com.example.szojcodesandbox.controller;

import com.example.szojcodesandbox.template.CppNativeCodeSandbox;
import com.example.szojcodesandbox.template.JavaNativeCodeSandbox;
import com.example.szojcodesandbox.model.ExecuteCodeRequest;
import com.example.szojcodesandbox.model.ExecuteCodeResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController("/")
public class MainController {
    // 定义鉴权请求头和密钥
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";
    @Resource
    private JavaNativeCodeSandbox javaNativeCodeSandbox;
    @Resource
    private CppNativeCodeSandbox cppNativeCodeSandbox;
    @GetMapping("/health")
    public String healthCheck() {
        return "ok";
    }
    @PostMapping("/executeCode")
    ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request,
                                    HttpServletResponse response){
        System.out.println(executeCodeRequest);
        System.out.println(request.getHeader(AUTH_REQUEST_HEADER));
        String header = request.getHeader(AUTH_REQUEST_HEADER);
        if(!AUTH_REQUEST_SECRET.equals(header)){
            response.setStatus(403);
            return null;
        }
        if(executeCodeRequest == null){
            throw new RuntimeException("请求参数为空");
        }
        if("java".equals(executeCodeRequest.getLanguage()))
            return javaNativeCodeSandbox.executeCode(executeCodeRequest);
        else
            return cppNativeCodeSandbox.executeCode(executeCodeRequest);
    }


}
